﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Bluetooth_Fan.HardwareInfo;
using Bluetooth_Fan.Classes;


namespace Bluetooth_Fan
{
    /// <summary>
    /// 设备状态参数
    /// </summary>
    public partial class DataUpFrom : Form
    {
        BleFan_MainForm MainForm;
        public DataUpFrom()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 实例化
        /// </summary>
        /// <param name="MainForm"></param>
        public DataUpFrom(Form Form)
        {
            InitializeComponent();
            MainForm = (BleFan_MainForm)Form;
            MainForm.EventDeADCStatus += OnDeADCStatus;
        }
        private void SYS_Staus_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;     //不关闭窗口
            }
        }
        #region   事件及委托
        /// <summary>
        /// 调试输出事件
        /// </summary>
        public event Action<string> EvenDebugLog;
        private void OnEvenDebugLog(string str)
        {
            Debug.WriteLine(str);
            if (EvenDebugLog != null)
            {
                EvenDebugLog(str);
            }
        }





        /// <summary>
        /// 接收到设备发来的ADC数据帧    1字节命令  1字节数据长度  X字节数据
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="Data"></param>
        private void OnDeADCStatus(object obj, byte[] Data)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<object, byte[]>(OnDeADCStatus), obj, Data);
            }
            else
            {
                if (Data[0] == ((byte)SYS_USER_COMM_Enum.Rep_SYS_State))
                {
                    byte[] CmmData = new byte[Data.Length - 2];
                    Array.Copy(Data, 2, CmmData, 0, CmmData.Length);
                    textBox21.Text = BitConverter.ToUInt16(CmmData, 0).ToString();
                    textBox20.Text = BitConverter.ToUInt16(CmmData, 2).ToString() + " MV";

                    textBox1.Text = BitConverter.ToUInt16(CmmData, 4).ToString();
                    textBox5.Text = BitConverter.ToUInt16(CmmData, 6).ToString() + " MV";

                    textBox2.Text = BitConverter.ToUInt16(CmmData, 8).ToString();
                    textBox4.Text = BitConverter.ToUInt16(CmmData, 10).ToString();

                    textBox8.Text = BitConverter.ToUInt16(CmmData, 12).ToString() + " mC";
                    textBox6.Text = BitConverter.ToUInt16(CmmData, 14).ToString();

                    textBox3.Text = BitConverter.ToUInt16(CmmData, 16).ToString();
                    textBox7.Text = BitConverter.ToUInt16(CmmData, 18).ToString() + "MV";
                }
            }
        }


        #endregion
        /// <summary>
        /// DES加密 秘钥  必须为 8个字符
        /// </summary>
        private static string Bluetooth_Fan_DES_KEY = "";

        /// <summary>
        /// DES加密 向量  必须为 8个字节
        /// </summary>
        private static string Bluetooth_Fan_DES_IV = "";

        /// <summary>
        /// 扫描用户输入 加密秘钥及 加密向量是否输入正常   返回True 正常
        /// </summary>
        /// <returns>返回True 正常</returns>
        private bool Scan_KEY_and_IV_data()
        {
            if ((textBox18.Text.Length != 8) || (textBox19.Text.Length != 8))
            {
                MessageBox.Show("加密秘钥及加密向量必须为8个字符！", "加密参数设置错误");
                Bluetooth_Fan_DES_KEY = "";
                Bluetooth_Fan_DES_IV = "";
                return false;
            }
            Bluetooth_Fan_DES_KEY = textBox18.Text;
            Bluetooth_Fan_DES_IV = textBox19.Text;
            return true;
        }

        /// <summary>
        /// 打开或者保存 支持的文件类型
        /// </summary>
        public const string Bluetooth_Fan_Filter = "Fan file(*.Fan)|*.Fan|所有文件(*.*)|*.*";

        /// <summary>
        /// 打开设备固件 文件类型
        /// </summary>
        public const string Bluetooth_Fan_Bin_Filter = "Bin file(*.Bin)|*.bin|所有文件(*.*)|*.*";


        /// <summary>
        /// 对加密的字节数组解密   返回解密数据
        /// </summary>
        /// <param name="Encode_Bytes">加密后的数组数据</param>
        /// <returns>解密后的数组数据</returns>
        public byte[] Return_Decode_Bytes_data(byte[] Encode_Bytes)
        {
            string File_Hex_string = "";
            //解密  得到的是 十六进制 的字符串表达形式  比如 0X11 为 “11”
            File_Hex_string = MY_DES_Encrypt.DES_Decode_String(Encoding.ASCII.GetString(Encode_Bytes), Bluetooth_Fan_DES_KEY, Bluetooth_Fan_DES_IV);
            if (File_Hex_string != null)
            {
                byte[] File_Bin = new byte[File_Hex_string.Length / 2];
                for (int i = 0; i < (File_Hex_string.Length / 2); i++)
                {
                    string data_bf = File_Hex_string.Substring(i * 2, 2);  //得到中间过段的字符串
                    File_Bin[i] = Convert.ToByte(data_bf, 16);  //string转换成 HEX
                }
                return File_Bin;
            }
            return null;
        }



        /// <summary>
        /// 打开加密固件文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            if (Scan_KEY_and_IV_data() == true)
            {
                string File_Path = "";
                //打开文件路径
                File_Path = Open_File("打开加密固件", Bluetooth_Fan_Filter);
                if (File_Path != null)
                {
                    textBox9.Text = File_Path;
                    byte[] File_Bytes;    //文件数据
                    File_Bytes = Read_File_Data_Bin(File_Path);  //得到加密文件的数据
                    if (File_Bytes != null)
                    {
                        Return_Decode_Bytes_data(File_Bytes);     //加密文件数据解密   并返回解密后的数据
                    }
                }
            }
        }



        /// <summary>
        /// 打开文件   并返回文件目录
        /// </summary>
        /// <param name="Title">选择文件窗口提示</param>
        /// <param name="Filter">打开文件类型 如 "bin file(*.bin)|*.bin|所有文件(*.*)|*.*"</param>
        /// <returns></returns>
        private string Open_File(string Title, string Filter)
        {
            openFileDialog1.Title = Title;
            openFileDialog1.Filter = Filter;    //需要打开的文件类型  
            openFileDialog1.InitialDirectory = Application.StartupPath;   //打开文件路径
            openFileDialog1.CheckPathExists = true;  //路径不存在显示警告
            if (openFileDialog1.ShowDialog() == DialogResult.OK)   //如果点击确定
            {
                return openFileDialog1.FileName;
            }
            return null;
        }

        /// <summary>
        /// 读取制定路径文件数据   返回其数据
        /// </summary>
        /// <param name="File_Path"></param>
        /// <returns></returns>
        public byte[] Read_File_Data_Bin(string File_Path)
        {
            try
            {
                string file_path = File_Path;
                FileStream Bin_File = new FileStream(file_path, FileMode.Open, FileAccess.Read);
                byte[] File_Data = new byte[Bin_File.Length];
                int len = 0;
                len = Bin_File.Read(File_Data, 0, (int)Bin_File.Length);
                return File_Data;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return null;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string File_Path = Open_File("打开固件", Bluetooth_Fan_Bin_Filter);
            if (File_Path != null)
            {
                textBox14.Text = File_Path;
            }
        }
        /// <summary>
        /// 用户文件数据 打包 后 DES加密   返回加密好的字符串
        /// </summary>
        /// <param name="User_data">用户需要加密的数据</param>
        /// <param name="KEY64">加密秘钥 必须为8个字符</param>
        /// <param name="IV64">加密向量 必须为8个字符</param>
        /// <returns>返回加密后的数据 字符串</returns>
        public string User_DES_Encode_data(byte[] User_data, byte[] KEY64, byte[] IV64)
        {
            string Bin_String = "";
            for (int i = 0; i < User_data.Length; i++)
            {
                Bin_String += User_data[i].ToString("X2");  //转换成HEX 字符串
            }

            string Encode_Bin = "";   //加密后的数据   需要写入加密文件中
            Encode_Bin = MY_DES_Encrypt.DES_Encode_String(Bin_String, Encoding.ASCII.GetString(KEY64), Encoding.ASCII.GetString(IV64)); //加密
            Encoding.ASCII.GetBytes(Encode_Bin);
            return Encode_Bin;
        }


        /// <summary>
        ///  创建文件并写入文件数据   返回文件目录  
        /// </summary>
        /// <param name="File_Data">创建的文件里面的数据</param>
        /// <param name="Title">窗口提示</param>
        /// <param name="Filter">文件类型 "bin file(*.bin)|*.bin|所有文件(*.*)|*.*" </param>
        /// <returns>创建的文件路径</returns>
        public string createCombinBinFile(byte[] File_Data, string Title, string Filter)
        {
            saveFileDialog1.Title = Title;
            saveFileDialog1.InitialDirectory = Application.StartupPath;  //默认本程序工程目录
            saveFileDialog1.Filter = Filter;
            saveFileDialog1.RestoreDirectory = true;

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)  //如果用户点击确定
            {
                string fileName = saveFileDialog1.FileName;  //得到文件名及路径
                Stream wStream = new FileStream(fileName, FileMode.Create);   //创建文件
                BinaryWriter strWrite = new BinaryWriter(wStream);            //定义写文件对象   及数据格式
                strWrite.Write(File_Data);  //写入数据
                strWrite.Close();  //关闭文件
                return fileName;
            }
            return saveFileDialog1.FileName;
        }

        /// <summary>
        /// 加密保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            if (Scan_KEY_and_IV_data() == true)
            {
                if (textBox14.Text != "")   //如果不是空路径
                {
                    byte[] File_Data;   //文件数据
                    //读取文件数据
                    File_Data = Read_File_Data_Bin(textBox14.Text);
                    if (File_Data != null)
                    {
                        string DES_Encode_data = "";
                        //加密输出
                        DES_Encode_data = User_DES_Encode_data(File_Data, Encoding.ASCII.GetBytes(Bluetooth_Fan_DES_KEY), Encoding.ASCII.GetBytes(Bluetooth_Fan_DES_IV));
                        //数据转换成 Byte数组
                        File_Data = Encoding.ASCII.GetBytes(DES_Encode_data);
                        //创建文件
                        textBox15.Text = createCombinBinFile(File_Data, "选择加密文件保存路径", Bluetooth_Fan_Filter);
                    }
                }
                else
                {
                    MessageBox.Show("请打开固件", "错误");
                }
            }
        }

        /// <summary>
        /// 打开密文
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button6_Click(object sender, EventArgs e)
        {
            string File_Path = Open_File("打开密文", Bluetooth_Fan_Filter);
            if (File_Path != null)
            {
                textBox17.Text = File_Path;
            }
        }

        /// <summary>
        /// 解密保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            if (Scan_KEY_and_IV_data() == true)
            {
                if (textBox17.Text != "")
                {
                    string File_Path = "";
                    File_Path = textBox17.Text;
                    byte[] File_Bytes;    //文件数据
                    File_Bytes = Read_File_Data_Bin(File_Path);  //得到加密文件的数据
                    if (File_Bytes != null)
                    {
                        byte[] File_Bin_data;   //解密后数据
                        File_Bin_data = Return_Decode_Bytes_data(File_Bytes);     //加密文件数据解密   并返回解密后的数据
                        //创建文件
                        textBox16.Text = createCombinBinFile(File_Bin_data, "选择解密文件保存路径", Bluetooth_Fan_Filter);
                    }
                }
            }

        }
    }
}
